/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <iostream>
#include "myFunction.h"

int addTwoNumberPlus(int valuePlus, ListNode *l1, ListNode *l2)
{
    if (l1 != NULL)
    {
        return valuePlus + l1->val + l2->val;
    }
    else
    {
        return valuePlus + l2->val;
    }
}

ListNode *Solution::addTwoNumbers(ListNode *l1, ListNode *l2)
{
    if (l1 == NULL || l2 == NULL)
    {
        return NULL;
    }

    int digit_10 = 0;
    int digit_1 = 0;
    ListNode *result = new ListNode(0);
    ListNode *Header = result;

    while (l1->next != NULL && l2->next != NULL)
    {
        int tmpResult = addTwoNumberPlus(digit_10, l1, l2);
        digit_10 = tmpResult / 10;
        digit_1 = tmpResult % 10;
        result->next = new ListNode(digit_1);
        result = result->next;
        l1 = l1->next;
        l2 = l2->next;
    }

    int tmpResult = addTwoNumberPlus(digit_10, l1, l2);
    digit_10 = tmpResult / 10;
    digit_1 = tmpResult % 10;
    result->next = new ListNode(digit_1);
    result = result->next;

    ListNode *lastNumber = NULL;
    if (l1->next != NULL)
    {
        lastNumber = l1->next;
    }
    else if (l2->next != NULL)
    {
        lastNumber = l2->next;
    }

    if (lastNumber != NULL)
    {
        while (lastNumber->next != NULL)
        {
            int tmpResult = addTwoNumberPlus(digit_10, NULL, lastNumber);
            digit_10 = tmpResult / 10;
            digit_1 = tmpResult % 10;
            result->next = new ListNode(digit_1);
            result = result->next;
            lastNumber = lastNumber->next;
        }
        tmpResult = addTwoNumberPlus(digit_10, NULL, lastNumber);
        digit_10 = tmpResult / 10;
        digit_1 = tmpResult % 10;
        result->next = new ListNode(digit_1);
        result = result->next;
    }
    if (digit_10 > 0)
    {
        result->next = new ListNode(digit_10);
    }

    ListNode *tmpHeader = Header->next;
    free(Header);

    return tmpHeader;
}
